package com.coffee.web.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.coffee.admin.api.common.service.RedisService;
import com.coffee.core.anotation.LoginCheck;
import com.coffee.core.anotation.LoginStatus;
import com.coffee.core.entity.SiteContextThreadLocal;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginSatutsInterceptor implements HandlerInterceptor {
    private final static Logger LOG = LoggerFactory.getLogger(LoginSatutsInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {

        HandlerMethod methodHandler = null;
        if (handler instanceof HandlerMethod) {
            methodHandler = (HandlerMethod) handler;
        } else {
            return true;
        }
        // 登录状态校验
        LoginStatus loginStatus = methodHandler.getMethodAnnotation(LoginStatus.class);
        if (loginStatus == null) {
            // 不需要校验登录状态
            return true;
        }
        boolean isLogin = isLogin();
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("isLogin", isLogin);
        data.put("code", "unLogin");
        data.put("message", "您还尚未登录");
        response.getWriter().write(JSONObject.toJSONString(data));
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {

    }

    private boolean isLogin() {
        String token = SiteContextThreadLocal.get().getCtoken();
        if (StringUtils.isEmpty(token)) {
            return false;
        }
        return true;
    }
}
